package com.eshop.config;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 这个配置类主要用于设置Spring MVC对跨域请求的支持以及静态资源的处理规则，
 * 确保前端应用能够正确访问服务器端的资源和接口。
 */
@Configuration(proxyBeanMethods = false)
@EnableWebMvc
public class ConfigurerAdapter implements WebMvcConfigurer
{
    @Value("${file.path}")
    private String path;
    @Value("${file.avatar}")
    private String avatar;
    
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(Boolean.valueOf(true));
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.setMaxAge(Long.valueOf(18000L));
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter((CorsConfigurationSource)source);
    }
    
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        final String avatarUtl = "file:" + this.avatar.replace("\\", "/");
        final String pathUtl = "file:" + this.path.replace("\\", "/");
        // 映射所有以 /avatar/** 开始的请求到本地文件系统中由 this.avatar 指定的目录，并且不进行缓存（setCachePeriod(0)）
        registry.addResourceHandler(new String[] { "/avatar/**" }).addResourceLocations(new String[] { avatarUtl }).setCachePeriod(Integer.valueOf(0));
        registry.addResourceHandler(new String[] { "/file/**" }).addResourceLocations(new String[] { pathUtl }).setCachePeriod(Integer.valueOf(0));
        registry.addResourceHandler(new String[] { "/**" }).addResourceLocations(new String[] { "classpath:/META-INF/resources/" }).setCachePeriod(Integer.valueOf(0));
    }
}
